package specmodel

import (
	"strconv"
	"web_server/model"
)

type SpecModel struct {
	Id   int64  `json:"id"`
	Name string `json:"name"`
	Info string `json:"info"`
	Rest int    `json:"rest"`
}

func GetSpecModel(id int64) *SpecModel {
	var sm *SpecModel = new(SpecModel)
	if err := model.DBSlaveRand().Get(sm, "SELECT id, name, info, rest FROM t_fruit_species where id = ?", id); err != nil {
		// panic(err)
		return nil
	}
	return sm
}

func GetSpecList(pagenum int64) ([]SpecModel, int64) {
	var smlist []SpecModel
	var specNum int64
	if err := model.DBSlaveRand().Get(&specNum, "SELECT count(*) FROM t_fruit_species"); err != nil {
		panic(err)
	}
	pagemax := (specNum + 19) / 20
	if pagenum > pagemax {
		pagenum = pagemax
	}
	if err := model.DBSlaveRand().Select(&smlist, "SELECT id, name, info, rest FROM t_fruit_species LIMIT 20 OFFSET ?", (pagenum-1)*20); err != nil {
		panic(err)
	}
	return smlist, pagemax
}

func SetSpecAdd(sm SpecModel) error {
	_, err := model.DBMaster().Exec("INSERT INTO t_fruit_species (name, info, rest) VALUES (?, ?, ?)", sm.Name, sm.Info, sm.Rest)
	return err
}

func SetSpecEdit(sm SpecModel) error {
	_, err := model.DBMaster().Exec("UPDATE t_fruit_species SET name = ?, info = ?, rest = ? WHERE id = ?", sm.Name, sm.Info, sm.Rest, sm.Id)
	return err
}

func SetSpecDel(ids []int) error {
	idsStr := strconv.Itoa(ids[0])
	for i := 1; i < len(ids); i++ {
		idsStr += ","
		idsStr += strconv.Itoa(ids[i])
	}
	_, err := model.DBMaster().Exec("DELETE FROM t_fruit_species WHERE id IN(" + idsStr + ")")
	return err
}
